package com.jxwifi.cloud.quickclean.upgrade;

import android.content.Context;
import android.util.Log;

import com.jxwifi.cloud.quickclean.bean.FileInfo;
import com.jxwifi.cloud.quickclean.bean.ThreadDAO;
import com.jxwifi.cloud.quickclean.bean.ThreadDAOImpl;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import static com.jxwifi.cloud.quickclean.upgrade.UpdateService.DOWNLOAD_PATH;
import static com.jxwifi.cloud.quickclean.upgrade.UpdateService.FILE_NAME;

/**
 * Created by user on 2016/12/19.
 */

public class DownLoadUtil {
    private Context context;
    private FileInfo fileInfo;
    private ThreadDAO threadDAO;
    private int finished = 0;
    public boolean isPause = false;

    public DownLoadUtil(Context context, FileInfo fileInfo) {
        this.context = context;
        this.fileInfo = fileInfo;
        if (threadDAO == null) {
            threadDAO = new ThreadDAOImpl(context);
        }
    }


    public void download() {
        List<FileInfo> lists = threadDAO.get(fileInfo.getUrl());
        FileInfo info = null;
        if (lists.size() == 0) {
            //第一次下载不改变
            //创建子线程下载
            new MyThread(fileInfo).start();
        } else {
            //中间开始的
            info = lists.get(0);
            if (fileInfo.getLength() == info.getLength()) { //判断大小是否一致，如果相同继续下载，否则删除之前数据从新下载
                new MyThread(info).start();
            } else {
                threadDAO.delete(info.getUrl());
                new MyThread(fileInfo).start();
            }
        }
    }

    class MyThread extends Thread {
        private FileInfo info = null;

        public MyThread(FileInfo threadInfo) {
            this.info = threadInfo;
        }

        @Override
        public void run() {
            //向数据库添加线程信息
            if (!threadDAO.isExits(info.getUrl())) {
                threadDAO.insert(info);
            }
            HttpURLConnection urlConnection = null;
            RandomAccessFile randomFile = null;
            InputStream inputStream = null;
            try {
                URL url = new URL(info.getUrl());
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(3000);
                urlConnection.setRequestMethod("GET");
                //设置下载位置
                int start = info.getStart() + info.getNow();
                urlConnection.setRequestProperty("Range", "bytes=" + start + "-" + info.getLength());

                //设置文件写入位置
                //创建一个本地文件
                File file = new File(DOWNLOAD_PATH, FILE_NAME);
                randomFile = new RandomAccessFile(file, "rwd");
                randomFile.seek(start);

                finished += info.getNow();
                //下载任务
                //读取数据
                if (urlConnection.getResponseCode() == 200) {//HttpStatus.SC_PARTIAL_CONTENT
                    //获得文件流
                    inputStream = urlConnection.getInputStream();
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    long time = System.currentTimeMillis();
                    while ((len = inputStream.read(buffer)) != -1) {
                        //写入文件
                        randomFile.write(buffer, 0, len);

                        finished += len;

                        //看时间间隔，时间间隔大于500ms再发
                        if (System.currentTimeMillis() - time > 1000) {
                            time = System.currentTimeMillis();
                            Log.w("test", "Handler" + finished * 100 / fileInfo.getLength());
                            EventBus.getDefault().post(finished * 100 / fileInfo.getLength(), "e-Netfinished");
                        }

                        //判断是否是暂停状态
                        if (isPause) {
                            threadDAO.update(info.getUrl(), finished);
                            return; //结束循环
                        }
                    }
                    EventBus.getDefault().post(true, "e-downOrver");
                    //删除线程信息
                    threadDAO.delete(info.getUrl());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
                try {
                    if (randomFile != null)
                        randomFile.close();
                    if (inputStream != null)
                        inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void delete(FileInfo info) {
        threadDAO.delete(info.getUrl());
    }
}
